<template>
  <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }" class="home-link">
      <el-icon><HomeFilled /></el-icon>
      返回首页
    </el-breadcrumb-item>
    <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index" :to="item.path">
      {{ item.name }}
    </el-breadcrumb-item>
  </el-breadcrumb>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { HomeFilled } from '@element-plus/icons-vue';

const route = useRoute();
const breadcrumbs = ref([]);

// 根据路由生成面包屑
const generateBreadcrumbs = () => {
  const { path, meta, matched } = route;
  
  // 清空当前面包屑
  breadcrumbs.value = [];
  
  // 根据路由匹配的路径生成面包屑
  if (matched && matched.length > 1) {
    // 跳过第一个匹配项，因为它是管理员布局
    matched.slice(1).forEach(item => {
      if (item.meta && item.meta.title) {
        breadcrumbs.value.push({
          name: item.meta.title,
          path: item.path
        });
      }
    });
  } else {
    // 如果没有匹配的路径，则根据当前路径生成
    const pathParts = path.split('/').filter(Boolean);
    
    if (pathParts.length > 1) {
      // 跳过 'admin' 部分
      const currentPath = pathParts[1];
      
      // 根据路径生成面包屑名称
      let breadcrumbName = '';
      
      switch (currentPath) {
        case 'users':
          breadcrumbName = '用户管理';
          break;
        case 'categories':
          breadcrumbName = '类别管理';
          break;
        case 'attractions':
          breadcrumbName = '景点管理';
          break;
        case 'comments':
          breadcrumbName = '评论管理';
          break;
        default:
          breadcrumbName = '控制面板';
      }
      
      breadcrumbs.value.push({
        name: breadcrumbName,
        path: `/admin/${currentPath}`
      });
    }
  }
};

// 监听路由变化，更新面包屑
watch(() => route.path, generateBreadcrumbs, { immediate: true });
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}

/* 返回首页链接的样式 */
.home-link :deep(.el-breadcrumb__inner) {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #409EFF !important;
  font-weight: bold;
  transition: all 0.3s;
  height: 100%;
}

.home-link :deep(.el-breadcrumb__inner) span {
  display: flex;
  align-items: center;
  line-height: normal;
}

.home-link :deep(.el-breadcrumb__inner):hover {
  color: #66b1ff !important;
  transform: scale(1.05);
}

.home-link :deep(.el-icon) {
  margin-right: 5px;
  display: flex;
  align-items: center;
}
</style> 